﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UI.Lib;
using Components;
using System.Threading;

namespace UI.StorageManagement
{
    public partial class FrmStoTranMedit : UI.ParentForm.BaseMedit
    {
        private bool isReadOnly = false;

        private DateTime now = DateTime.MinValue;

        public FrmStoTranMedit(string modulecode, string action, string text, string key)
            : base(modulecode, action)
        {
            Control.CheckForIllegalCrossThreadCalls = false;

            InitializeComponent();

            this.Text = text;
            this.Key = key;
            this.MaxStateFlag = true;//打开页面后让窗口最大化

            this.SaveCallFuntion = "Sto7a00Manager$SaveData"; //保存的方法
            IsAfterSaveCloseWin = false;
            if (!string.IsNullOrEmpty(this.Key))
            {
                IsAfterSaveCloseWin = true;
                LoadData();

                if ("R" == Action || "K" == Action)
                {
                    new Thread(new ThreadStart(delegate
                    {
                        now = Context.GetServerDate();

                        if ("K" == action) this.tbSummary.SetValue("sendate", now.ToShortDateString());
                        if ("R" == action) this.tbSummary.SetValue("recdate", now.ToShortDateString());
                    })).Start();
                }
            }

            LoadDefaultValue();
        }

        protected override void PageInit()
        {
            this.tbSummary.DefaultWidth = 100;
        }

        protected void LoadDefaultValue()
        {
            object val = null;
            if ("A" == this.Action && Validation.IsNull(tbSummary.GetValue("muser")))
            {
                this.tbSummary.SetValue("muser", Context.LoginName);
            }

            if ("K" == this.Action)//发货
            {
                if (Validation.IsNull(tbSummary.GetValue("senduser")))
                {
                    this.tbSummary.SetValue("senduser", Context.LoginName);
                }

                for (int i = 0; i < this.dgvDtl.Rows.Count; i++)
                {
                    val = this.dgvDtl["tranqty", i].Value;
                    this.dgvDtl["sendqty", i].Value = val;


                    this.dgvDtl["sendamt", i].Value = Validation.ToDouble(Validation.ToDouble(val) *
              Validation.ToDouble(this.dgvDtl["tranprice", i].Value, 3));

                    CalcSummarySendamt();
                }
            }

            if ("R" == this.Action) //收货
            {
                if (Validation.IsNull(tbSummary.GetValue("recuser")))
                {
                    this.tbSummary.SetValue("recuser", Context.LoginName);
                }

                for (int i = 0; i < this.dgvDtl.Rows.Count; i++)
                {
                    val = this.dgvDtl["sendqty", i].Value;
                    this.dgvDtl["recqty", i].Value = this.dgvDtl["sendqty", i].Value;

                    this.dgvDtl["recamt", i].Value = Validation.ToDouble(Validation.ToDouble(val) *
              Validation.ToDouble(this.dgvDtl["tranprice", i].Value, 3));

                    CalcSummaryRecamt();
                }
            }
        }

        public override bool BeforePopWin(string name, ref string where, ref string[] others)
        {
            if (name == "outstocode" || name == "instocode")
            {
                //调入仓库和调出仓库不能是一样
                where = string.Format("statuscode = '1' {0} AND listid <> '{1}' ",
                        Context.GetAppKeyWhere("usercode", true),
                        this.tbSummary.GetValue(name == "outstocode" ? "instk" : "outstk"));
            }
            else if (name == "valuecode")//物流公司
            {
                where = string.Format("statuscode = '1' {0} ",
                        Context.GetAppKeyWhere("usercode", true));
            }

            return true;
        }

        protected override bool BeforeDtlPopUp(string name, ref string where, ref string[] others)
        {
            if ("productcode" == name)
            {
                string table = string.Format(@"(
SELECT a.productcode, a.muser, a.status, a.productname, a.bordqty, a.pamt,a.umdesc,a.pvlistid,
ISNULL((SELECT SUM(storageqty) FROM Sto6a00 z WHERE z.pid = a.listid AND z.storageid ='{1}'),0) AS instkqty,
ISNULL((SELECT SUM(storageqty) FROM Sto6a00 z WHERE z.pid = a.listid AND z.storageid ='{2}'),0) AS outstkqty,
a.listid
FROM
Pot3a00_view a
WHERE a.muser LIKE '{0}%' AND a.status = '1') T",
                Context.Comocde,
                Validation.ToString(this.tbSummary.GetValue("instk")),
                Validation.ToString(this.tbSummary.GetValue("outstk"))
                );

                others = new string[] { table };
            }

            return true;
        }

        //新增行后触发，用户只读概要
        protected override void AfterAddRow()
        {
            if (isReadOnly == true) return;

            this.tbSummary.Enable("outstocode", false);
            this.tbSummary.Enable("instocode", false);
        }

        protected override void AfterDelete()
        {
            if (this.dgvDtl.Rows.Count == 0)
            {
                this.tbSummary.Enable("outstocode", true);
                this.tbSummary.Enable("instocode", true);
                isReadOnly = false;
            }
        }

        protected override void AfterDtlValueChanged(string name, object value)
        {
            if ("tranqty" == name) //调拨数量改变时，计算调拨金额
            {
                this.dgvDtl.SetValue("tranamt", Validation.ToDouble(Validation.ToDouble(value) *
                Validation.ToDouble(this.dgvDtl.GetValue("tranprice")), 3));

                CalcSummaryAmtAndQty(); //计算毛利总额
            }
            else if ("sendqty" == name)
            {
                this.dgvDtl.SetValue("sendamt", Validation.ToDouble(Validation.ToDouble(value) *
               Validation.ToDouble(this.dgvDtl.GetValue("tranprice")), 3));

                CalcSummarySendamt(); //计算毛利总额
            }
            else if ("recqty" == name)
            {
                this.dgvDtl.SetValue("recamt", Validation.ToDouble(Validation.ToDouble(value) *
             Validation.ToDouble(this.dgvDtl.GetValue("tranprice")), 3));

                CalcSummaryRecamt(); //计算毛利总额
            }
        }

        //计算调拨总数量和总金额
        protected void CalcSummaryAmtAndQty()
        {
            double sum = 0;
            double sumtranamt = 0;
            foreach (DataGridViewRow dr in this.dgvDtl.Rows)
            {
                sum += Validation.ToDouble(dr.Cells["tranqty"].Value);
                sumtranamt += Validation.ToDouble(dr.Cells["tranamt"].Value);
            }

            this.tbSummary.SetValue("tranamtotal", Validation.ToDouble(sumtranamt, 3));
            this.tbSummary.SetValue("tranqtytotal", Validation.ToDouble(sum, 2));
        }

        private void CalcSummarySendamt()
        {
            double sumtranamt = 0;
            foreach (DataGridViewRow dr in this.dgvDtl.Rows)
            {
                sumtranamt += Validation.ToDouble(dr.Cells["sendamt"].Value);
            }

            this.tbSummary.SetValue("sendamtotal", Validation.ToDouble(sumtranamt, 3));
        }

        private void CalcSummaryRecamt()
        {
            double sumtranamt = 0;
            foreach (DataGridViewRow dr in this.dgvDtl.Rows)
            {
                sumtranamt += Validation.ToDouble(dr.Cells["recamt"].Value);
            }

            this.tbSummary.SetValue("recamtotal", Validation.ToDouble(sumtranamt, 3));
        }
        //加载修改数据
        private void LoadData()
        {
            base.LoadEditData(null, string.Format(" a.tranid ='{0}' ", this.Key));
            base.LoadDtlData(null, string.Format(" a.ptranid ='{0}' ", this.Key));

            if ("K" == this.Action)
            {
                this.dgvDtl.Focus(0, "sendqty");
            }
            else if ("R" == this.Action || "J" == this.Action)
            {
                this.dgvDtl.Focus(0, "recamt");
            }
        }
    }
}
